package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.UserReport;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class SoulReportApiImpl implements SoulReportApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override//保存当前登录用户的答卷对象
    public void save(UserReport report) {
        //构建条件
        Criteria criteria = Criteria.where("userId").is(report.getUserId());
        Query query = Query.query(criteria);
        //1.update对象
        Update update = new Update();
        update.set("soulPaperId",report.getSoulPaperId());
        update.set("scope",report.getScope());
        update.set("cover",report.getCover());
        update.set("genre",report.getGenre());
        update.set("conclusion",report.getConclusion());
        update.set("created",System.currentTimeMillis());
        update.set("updated",System.currentTimeMillis());
        //这个方法设置了条件，根据条件判断数据库里有没有数据
        // 有就保存，没有就更新
        mongoTemplate.upsert(query,update,report.getClass());

    }


    @Override//根据用户id和答卷id查询一次
    public UserReport findByIds(Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        return mongoTemplate.findOne(query, UserReport.class);
    }

    @Override//根据答卷id查询自己的答卷
    public UserReport findByReportId(String reportId) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(reportId));
        Query query = Query.query(criteria);
        return mongoTemplate.findOne(query, UserReport.class);
    }

    @Override//根据类型（狮子，兔子...）查询多个表对象
    public List<UserReport> findList(String genre) {
        Criteria criteria = Criteria.where("genre").is(genre);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query,UserReport.class);
    }
}
